package com.black.app.service.impl.my;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.black.app.domain.my.AppMyWaistlineDetail;
import com.black.app.domain.req.my.mydata.AppMyWaistlineDetailAddReq;
import com.black.app.service.my.AppMyWaistlineDetailService;
import com.black.app.mapper.my.AppMyWaistlineDetailMapper;
import com.black.common.exception.ServiceException;
import com.black.common.utils.MessageUtils;
import com.black.common.utils.SecurityUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

/**
* @author 18494
* @description 针对表【app_my_waistline_detail(腰围变化详情表)】的数据库操作Service实现
* @createDate 2024-10-23 20:49:29
*/
@Service
public class AppMyWaistlineDetailServiceImpl extends ServiceImpl<AppMyWaistlineDetailMapper, AppMyWaistlineDetail>
    implements AppMyWaistlineDetailService{

    @Override
    public boolean addWaistline(AppMyWaistlineDetailAddReq req) {
        // 获取用户id
        req.setUserId(SecurityUtils.getAppLoginUser().getUserId());

        // 判断日期是否已经存在
        if (this.baseMapper.exists(new LambdaQueryWrapper<AppMyWaistlineDetail>().eq(AppMyWaistlineDetail::getDate, req.getDate()))) {
            throw new ServiceException(MessageUtils.message("app.my.detail.date.exists"));
        }

        // 获取日期最大的腰围信息
        AppMyWaistlineDetail maxWaistline = this.baseMapper.selectOne(new LambdaQueryWrapper<AppMyWaistlineDetail>()
                .eq(AppMyWaistlineDetail::getUserId, req.getUserId())
                .orderByDesc(AppMyWaistlineDetail::getDate).last("limit 1"));

        if (maxWaistline == null) {
            req.setChanges(0.0);
        }
        req.setChanges(req.getWaistline() - maxWaistline.getWaistline());

        AppMyWaistlineDetail newEntity = new AppMyWaistlineDetail();
        BeanUtils.copyProperties(req, newEntity);
        boolean save = this.save(newEntity);

        return save;
    }

    @Override
    public PageInfo<AppMyWaistlineDetail> getWaistline(AppMyWaistlineDetailAddReq req) {
        req.setUserId(SecurityUtils.getAppLoginUser().getUserId());
        return PageHelper.startPage(req.getPageNum(), req.getPageSize()).doSelectPageInfo(() -> {
            this.baseMapper.getWaistline(req);
        });
    }

    @Override
    public boolean deleteById() {
        // 获取当前登录用户的用户id
        Long userId = SecurityUtils.getAppLoginUser().getUserId();
        // 删除AppMyWaistlineDetail表中id最大的数据并且userId等于当前登录用户的用户id
        int id = this.baseMapper.selectOne(new LambdaQueryWrapper<AppMyWaistlineDetail>()
                    .eq(AppMyWaistlineDetail::getUserId, userId)
                    .orderByDesc(AppMyWaistlineDetail::getId).last("limit 1")).getId();
        boolean result = this.removeById(id);
        return result;
    }
}




